package com.bestcem.xm.user.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.oss.enums.OssPathEnum;
import com.bestcem.xm.componet.filestorage.service.StorageService;
import com.bestcem.xm.user.controller.vo.FileInfoVO;
import com.bestcem.xm.user.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/7/17 21:27
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    /*@Resource
    private OssService ossService;*/
    @Autowired
    private StorageService storageService;
    private static final String CONTRACT_DOCUMENTS_REMARK = "USER共用文件上传类";

    @Override
    public ServiceResult<FileInfoVO> uploadFile(MultipartFile file) {
        //byte[] bytes = null;
        //try {
        //    bytes = file.getBytes();
        //} catch (IOException e) {
        //    log.error("[common] 获取上传文件数据失败");
        //}
        String originalFilename = file.getOriginalFilename();
        originalFilename = Objects.nonNull(originalFilename) ? originalFilename : "";
        String fileName = cn.hutool.core.date.DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN)
                + RandomUtil.randomNumbers(6) + originalFilename.replace(" ", "");
        //String url = ossService.uploadFile(bytes, fileName, OssPathEnum.USER, CONTRACT_DOCUMENTS_REMARK);
        String url = storageService.upload(file, fileName, OssPathEnum.USER.getPath(), new Dict()).getUrl();
        return ServiceResult.success(new FileInfoVO(url, fileName, null));
    }
}
